package com.dev.weixin.platform.controllers;

import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.security.login.beans.LoginUser;
import com.dev.security.login.service.LoginManager;
import com.dev.security.util.Response;
import com.dev.weixin.platform.beans.WXConfig;
import com.dev.weixin.platform.service.IWXBaseService;
import com.dev.weixin.platform.service.IWXConfigService;
import com.dev.weixin.utils.ObjectUtils;

/**
 * @author 飘渺青衣
 * @see
 */
@Controller
@RequestMapping("/wxconfig/")
public class WXConfigController {

	@Autowired
	private IWXConfigService wxConfigService;
	
	@Autowired
	private IWXBaseService wxBaseService;
	
	@Autowired
	private LoginManager loginManager;
	
	@RequestMapping("load")
	public @ResponseBody HashMap<String, Object> load(
				HttpServletRequest request, 
				HttpServletResponse response) {
		HashMap<String, Object> result = new LinkedHashMap<String, Object>();
		LoginUser loginUser = this.loginManager.getLoginUser(request, response);
		WXConfig config = this.wxConfigService.findWXConfig(loginUser.getUserId());
		result.put("config", config);
		result.put("address", wxBaseService.getFullPath(
				new StringBuilder().append("/weixin/")
				.append(loginUser.getUserId()).append("/listener").toString()));
		return result;
	}
	
	@RequestMapping("save")
	public @ResponseBody Response save(
				HttpServletRequest request, 
				HttpServletResponse response,
				WXConfig config) {
		ObjectUtils.trimToEmpty(config);
		LoginUser loginUser = this.loginManager.getLoginUser(request, response);
		config.setUserId(loginUser.getUserId());
		WXConfig t_config = this.wxConfigService.findWXConfigByOriginalId(config.getOriginalId());
		if(t_config != null) {
			if(!StringUtils.equals(t_config.getUserId(), config.getUserId())) {
				//其他人已经占用此原始ID
				return new Response(false, 1);
			}
			config.setCreateTime(t_config.getCreateTime());
		} else {
			config.setCreateTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
		}
		this.wxConfigService.save(config);
		return new Response(true, config);
	}
}
